package com.pi.pro.xcmg.am.was.fac.service;

import com.pi.config.LicenseProperties;
import com.pi.pro.xcmg.am.common.XcmgEncryptionSupport;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Slf4j
//@Component
public class LicenseValidationRunner implements CommandLineRunner {

    @Autowired
    private LicenseService licenseService;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private LicenseProperties licenseProperties;

    @Override
    public void run(String... args) throws Exception {
        String key="";
        RBucket<String> bucket=null;
        try {
            // XcmgEncryptionSupport.license();
            key = "LIC:XCMG:WH101//EXP";
            // 从加密文件加载授权信息
            licenseService.loadFromEncryptedFile();
            bucket = this.redissonClient.getBucket(key);
            if (bucket!=null){
                bucket.set(licenseProperties.getExpiryDate());
            }
            // 验证授权
            if (!licenseService.validateLicense()) {
                log.error("LicenseInvalidate.Check Work or ExpireDate");
                // 终止应用
                //System.exit(1);
            }else {
                log.info("LicenseValidate.");
            }
        } catch (Exception e) {
            log.error("=====================ERROR=====================");
            if (e!=null){
                if (e.getMessage()!=null){
                    log.error("::"+e.getMessage());
                    System.out.println("::"+e.getMessage());
                }else {
                    log.error("::...");
                    System.out.println("::...");
                }
            }

            e.printStackTrace();
            log.error("LicenseCheckError.Error: " + e.getMessage());

            System.out.println(e.getMessage());
            // 终止应用
           System.exit(1);
        }
    }
}
    